package com.lomoye.easy.backend;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.lomoye.easy.domain.ConfigurableSpider;
import com.lomoye.easy.service.ConfigurableSpiderService;
import com.lomoye.easy.utils.SerializationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 2020/4/10 14:18
 * yechangjun
 * 导入示例爬虫配置
 */
@Slf4j
@Service
public class ImportExampleService extends Thread {

    @Autowired
    private ConfigurableSpiderService configurableSpiderService;

    @Override
    public void run() {
        //如果数据库里一个爬虫都没有启动的时候创建示例爬虫
        if (configurableSpiderService.count() > 0) {
            return;
        }

        String path = getClass().getResource("/example").getPath();

        File exampleDir = new File(path);
        String[] files = exampleDir.list();
        if (files == null) {
            return;
        }

        for (String fileName : files) {
            File file = new File(path + File.separator + fileName);
            try {
                doImport(Files.toString(file, Charsets.UTF_8));
            } catch (IOException e) {
                log.error("doImport spider error", e);
            }
        }
    }

    private void doImport(String config) {
        ConfigurableSpider configurableSpider = SerializationUtil.str2Object(config, ConfigurableSpider.class);
        configurableSpider.setCreateTime(LocalDateTime.now());
        configurableSpider.setModifyTime(LocalDateTime.now());
        configurableSpiderService.save(configurableSpider);
    }
}
